package com.gcit.seniorWish.web.modular.examinee.controller;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gcit.seniorWish.core.base.controller.BaseController;
import com.gcit.seniorWish.core.base.tips.Tip;
import com.gcit.seniorWish.core.exception.GunsException;
import com.gcit.seniorWish.core.node.SelectNode;
import com.gcit.seniorWish.core.util.ToolUtil;

import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.persistence.model.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;

import org.springframework.web.bind.annotation.RequestParam;

import com.gcit.seniorWish.web.common.constant.Const;
import com.gcit.seniorWish.web.common.constant.enums.ManagerStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.RoleEnum;
import com.gcit.seniorWish.web.common.constant.enums.UserTypeEnum;
import com.gcit.seniorWish.web.common.constant.factory.PageFactory;
import com.gcit.seniorWish.web.common.persistence.dao.SeniorSchoolClassMapper;
import com.gcit.seniorWish.web.common.persistence.dao.SeniorSchoolMapper;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorExamineeService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolClassService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolService;
import com.gcit.seniorWish.web.modular.examinee.warpper.ClassWarpper;
import com.gcit.seniorWish.web.modular.system.service.IRoleService;
import com.gcit.seniorWish.web.modular.system.service.IUserMgrService;

import cn.hutool.core.util.StrUtil;

/**
 * 班级控制器
 *
 * @author tonglu
 * @Date 2018-03-19 16:56:07
 */
@Controller
@RequestMapping("/seniorSchoolClass")
public class SeniorSchoolClassController extends BaseController {

	private String PREFIX = "/examinee/class";

	@Resource
	private SeniorSchoolClassMapper seniorSchoolClassMapper;

	@Resource
	private SeniorSchoolMapper seniorSchoolMapper;

	@Autowired
	private ISeniorSchoolClassService seniorSchoolClassService;

	@Autowired
	private IUserMgrService userMgrService;

	@Autowired
	IRoleService roleService;

	@Autowired
	ISeniorSchoolService seniorSchoolService;

	@Autowired
	private ISeniorExamineeService seniorExamineeService;

	/**
	 * 数据列表
	 */
	@RequestMapping("")
	public String school(Model model) {

		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 登录人为班主任
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), ShiroKit.getUser().getClassId()));
		} else if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			model.addAttribute("schoolu",
					seniorSchoolService.listSchoolForSelect2(null, ShiroKit.getUser().getSchoolId()));
			model.addAttribute("classu", seniorSchoolClassService.listSchoolClassForSelect2(null,
					ShiroKit.getUser().getSchoolId(), null));
		} else {
			model.addAttribute("schoolu", null);
			model.addAttribute("classu", null);
		}
		return PREFIX + "/class.html";
	}

	/**
	 * 获取班级列表
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(String seniorSchoolId,
	                   @RequestParam(required = false) String seniorClassCode,
	                   @RequestParam(required = false) String senoirClassName) {
		Page<Map<String, Object>> page = new PageFactory().defaultPage();
		EntityWrapper<SeniorSchoolClass> ew = new EntityWrapper<SeniorSchoolClass>();
		if(StrUtil.isNotBlank(seniorSchoolId)){
			ew.eq("senoir_school_id",seniorSchoolId);
		}
		if (StrUtil.isNotBlank(seniorClassCode))
			ew.like("senior_class_code", seniorClassCode);
		if (StrUtil.isNotBlank(senoirClassName))
			ew.like("senoir_class_name", senoirClassName);
		if (UserTypeEnum.SCHOOL.getValue() == ShiroKit.getUser().getType()) {// 登录人为学校管理员
			ew.eq("senoir_school_id", ShiroKit.getUser().getSchoolId());
		}
		seniorSchoolClassService.selectMapsPage(page, ew);
		page.setRecords((List<Map<String, Object>>) new ClassWarpper(page.getRecords()).warp());
		return packForBT(page);
	}

	/**
	 * 跳转到查编辑页面
	 */
	@RequestMapping("/edit")
	public String edit(SeniorSchoolClass schoolClass, Model model) {
		schoolClass = seniorSchoolClassMapper.selectById(schoolClass.getId());
		if (schoolClass == null) {
			schoolClass = new SeniorSchoolClass();
			model.addAttribute("schools", null);
		} else {
			model.addAttribute("schools",
					seniorSchoolService.listSchoolForSelect2(null, schoolClass.getSenoirSchoolId()));
		}
		model.addAttribute("schoolClass", schoolClass);
		return PREFIX + "/classEdit.html";
	}

	/**
	 * 班级保存
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/save")
	@ResponseBody
	public Tip save(SeniorSchoolClass schoolClass) {
		//判断该班级代号是否存在
		EntityWrapper<SeniorSchoolClass> ew = new EntityWrapper<>();
		ew.eq("senior_class_code", schoolClass.getSeniorClassCode());
		ew.eq("senoir_school_id", schoolClass.getSenoirSchoolId());
		//当id存在时，判断需要排除该记录
		if (StrUtil.isNotBlank(schoolClass.getId())) {
			ew.ne("id", schoolClass.getId());
		}
		if (this.seniorSchoolClassService.selectCount(ew) > 0) {// 该班级代号已存在
			throw new GunsException(BizExceptionEnum.SENIOR_CLASS_CODE_EXIST);
		}
		//id存在时，数据库存在
		if (StrUtil.isNotBlank(schoolClass.getId())) {
			//查询已经存在的班级信息，用于查询用户表中已经存在的用户（防止编号修改找不到用户）
			SeniorSchoolClass existClass = ConstantFactory.me().getSeniorSchoolClassById(schoolClass.getId());
			//编号不同时，需要查询修改后的形成的用户名在用户表中是否存在
			if (!schoolClass.getSeniorClassCode().equals(existClass.getSeniorClassCode())) {
				//查询到班级所属的学校
				SeniorSchool school = ConstantFactory.me().getSeniorSchoolById(existClass.getSenoirSchoolId());
				//新增数据时，查询班级对应的班级管理员所用账号在用户表中是否存在
				if (userMgrService.selectCount(Condition.create().eq("account", "szwz" + school.getSchoolCode() + schoolClass.getSeniorClassCode())) > 0) {// 用户名已存在
					throw new GunsException(BizExceptionEnum.USER_ALREADY_REG);
				}
			}
		} else {
			//查询到班级所属的学校
			SeniorSchool school = ConstantFactory.me().getSeniorSchoolById(schoolClass.getSenoirSchoolId());
			//新增数据时，查询班级对应的班级管理员所用账号在用户表中是否存在
			if (userMgrService.selectCount(Condition.create().eq("account", "szwz" + school.getSchoolCode() + schoolClass.getSeniorClassCode())) > 0) {// 用户名已存在
				throw new GunsException(BizExceptionEnum.USER_ALREADY_REG);
			}
		}

		seniorSchoolClassService.mergeSeniorSchoolClass(schoolClass);
		return SUCCESS_TIP;
	}

	/**
	 * 删除学校
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/remove")
	@ResponseBody
	public Tip remove(@RequestParam String classId) {
		if (ToolUtil.isEmpty(classId)) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}
		if (seniorExamineeService.selectCount(Condition.create().eq("senior_class_id", classId)) > 0) {
			throw new GunsException(BizExceptionEnum.CLASS_HAVE_EXAMINEE);
		}
		// 删除对应的用户
		SeniorSchoolClass seniorSchoolClass = seniorSchoolClassMapper.selectById(classId);
		SeniorSchool school = seniorSchoolMapper.selectById(seniorSchoolClass.getSenoirSchoolId());
		this.seniorSchoolClassMapper.deleteById(classId);
		User user = userMgrService.selectOne(Condition.create().eq("account",
				"szwz" + school.getSchoolCode() + seniorSchoolClass.getSeniorClassCode()));
		if (user != null) {
			userMgrService.deleteUser(user.getId());
		}
		return SUCCESS_TIP;
	}

	/**
	 * 查询班级列表 term 模糊查询
	 *
	 * @author tonglu
	 * @date 2018-03-19 下午 4:01
	 */
	@SuppressWarnings({"rawtypes", "unchecked"})
	@RequestMapping(value = "/listSchoolClassForSelect2")
	@ResponseBody
	public Object listSchoolClassForSelect2(String term, String schoolId) {
		Page<SelectNode> page = new Page();
		if (UserTypeEnum.TEACHING.getValue() == ShiroKit.getUser().getType()) {// 表示
			// 登录人为班主任
			page.setRecords(seniorSchoolClassService.listSchoolClassForSelect2(term, schoolId,
					ShiroKit.getUser().getClassId()));
		} else {
			page.setRecords(seniorSchoolClassService.listSchoolClassForSelect2(term, schoolId, null));
		}

		return packForSelect2(page);
	}

}
